#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>
#include <sys/time.h>

#define BUFF_LEN    1024
#define PORT    6789
#define SERVER_IP   "192.168.91.52"
//#define SERVER_IP   "127.0.0.1"

long getTimeUS() {
    struct timeval tv;
    gettimeofday(&tv, NULL);

    return tv.tv_sec*1000*1000 + tv.tv_usec;
}

int main(int argc, char *argv[])
{
    int fd = 0;
    int port = 5555;
    char Buffer[] = "Hello world";
    char recvBuf[BUFF_LEN] = {0};
    int size = 0;

    fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
    struct sockaddr_in clientAddr;
    clientAddr.sin_family = AF_INET;
    clientAddr.sin_port = htons(PORT);
    clientAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
    if (connect(fd, (struct sockaddr*)&clientAddr, sizeof(struct sockaddr)) < 0)
    {
        printf("connect error\n");
        return 0;
    }
    
    while (true) {
        long t1 = getTimeUS();
        send(fd, Buffer, strlen(Buffer), 0);
        size = recv(fd, recvBuf, BUFF_LEN, 0);
        recvBuf[size] = '\0';
        long t2 = getTimeUS();
        if (size > 0) {
            printf("[%ld]recv: %s\n", (t2-t1)/1000, recvBuf);
            fflush(stdout);
        }
        sleep(1);
    }

    close(fd);

    return 0;
}